package com.richinfo.demo.config.dao;

import java.io.IOException;

import javax.sql.DataSource;

import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

/**
* Created by WangXJ
* 2018-05-05 17:38
*/
@Configuration
public class SessionFactoryConfiguration {
	
	@Value("${mybatis_config_file}")
	private String mybatisConfigFilePath;
	
	@Value("${mapper_path}")
	private String mapperPath;
	
	@Value("${entity_package}")
	private String entityPackage;
	
	@Autowired
	private DataSource dataSource;
	

	@Bean(name = "sqlSessionFactory")
	public SqlSessionFactoryBean createSqlSessionFactoryBean() throws IOException {
		SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
		//指定MybatisConfig文件的路径
		sqlSessionFactoryBean.setConfigLocation(new ClassPathResource(mybatisConfigFilePath));
		//数据文件流处理对象
		PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
		//指定mapper文件扫描路径
		String packageSearchPath = PathMatchingResourcePatternResolver.CLASSPATH_URL_PREFIX +
								   mapperPath;
		sqlSessionFactoryBean.setMapperLocations(resolver.getResources(packageSearchPath));
		//指定DataSource
		sqlSessionFactoryBean.setDataSource(dataSource);
		//指定实体类package的扫描路径
		sqlSessionFactoryBean.setTypeAliasesPackage(entityPackage);
		
		return sqlSessionFactoryBean;
	}

}
